package org.example.leetcode.codeExecutor.service.impl;

import org.apache.commons.lang.text.StrSubstitutor;
import org.example.leetcode.codeExecutor.service.CodeExecuteFlow;
import org.example.leetcode.codeExecutor.utils.SSHTools;
import org.example.leetcode.common._enum.LanguageEnum;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service("JavaExecutor")
public class JavaExecutor extends CodeExecuteFlow {
    @Override
    public String getSuffix() {
        return LanguageEnum.JAVA.getSuffix();
    }

    @Override
    public LanguageEnum getLanguageEnum() {
        return LanguageEnum.JAVA;
    }

    @Override
    protected String compile(String fileUrl) {
        Map<String,String> map=new HashMap<>();
        map.put("compileCode","javac");
        map.put("fileUrl",fileUrl);
        map.put("targetUrl", SSHTools.BASE_URL+getLanguageEnum().getCode());
        String s="cd ${targetUrl} && ${compileCode} ${fileUrl}";
        StrSubstitutor strSubstitutor=new StrSubstitutor(map);
        String cmd = strSubstitutor.replace(s);
        try {
            SSHTools.SSHResult sshResult = SSHTools.getSSHTools().executeShell(cmd);
            return StringUtils.isEmpty(sshResult.getError())?null:sshResult.getError().substring(sshResult.getError().indexOf(":")+1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String getExecuteCmd(String execFile, String testFile) {
        Map<String,String> map=new HashMap<>();
        map.put("execFile",execFile);
        map.put("testFile",testFile);
        map.put("targetUrl",SSHTools.BASE_URL+getLanguageEnum().getCode());
        String s="cd ${targetUrl} && java ${execFile} < ${testFile}";
        StrSubstitutor strSubstitutor=new StrSubstitutor(map);
        String cmd = strSubstitutor.replace(s);
        return cmd;
    }

    @Override
    protected void getDeleteCmd(String execFile) {
        Map<String,String> map=new HashMap<>();
        map.put("execFile",execFile);
        map.put("targetUrl",SSHTools.BASE_URL+getLanguageEnum().getCode());
        String s="cd ${targetUrl} && rm -rf ${execFile}.class";
        StrSubstitutor strSubstitutor=new StrSubstitutor(map);
        String cmd = strSubstitutor.replace(s);
        try {
            SSHTools.getSSHTools().executeShell(cmd);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
